package com.cisdi.blog.service.impl;

import com.cisdi.blog.dao.CommentRepository;
import com.cisdi.blog.entity.Comment;
import com.cisdi.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2020年03月19日 16:38:00
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentRepository commentRepository;


    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        List<Comment> comments = commentRepository.findByBlogId(blogId, sort);
        return getNodeComment(comments);
    }

    @Transactional
    @Override
    public Comment saveComment(Comment comment) {
        Long parentCommentId = comment.getParentComment().getId();
        if (parentCommentId!=-1){
            comment.setParentComment(commentRepository.getOne(parentCommentId));
        }else {
            comment.setParentComment(null);
        }
        comment.setCreateTime(new Date());
        return commentRepository.save(comment);
    }

    @Override
    public List<Comment> getNodeComment(List<Comment> comments) {
        if (!CollectionUtils.isEmpty(comments)){
            List<Comment> collect = comments.stream().filter((comment) -> comment.getParentComment() == null).collect(Collectors.toList());
            for (Comment comment : collect) {
                List<Comment> replyComments = comment.getReplyComments();
                for (Comment replyComment : replyComments) {
                    getSencondComment(replyComment);
                }
                comment.setReplyComments(second);
                //清楚缓存区
                second = new ArrayList<>();
            }
            return collect;
        }
        return Collections.EMPTY_LIST;
    }

    /**
     * 存放所有子集
     */
    private List<Comment> second = new ArrayList<>();

    @Override
    public void getSencondComment(Comment comment) {
        second.add(comment);
        if (comment.getReplyComments().size()>0){
            List<Comment> replyComments = comment.getReplyComments();
            for (Comment replyComment : replyComments) {
                second.add(replyComment);
                if (replyComment.getReplyComments().size()>0){
                    getSencondComment(replyComment);
                }
            }
        }
    }
}
